package com.bwie.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.config.FreemarkerUtil;
import com.bwie.config.OSSFileUtil;
import com.bwie.mapper.*;
import com.bwie.pojo.*;
import com.bwie.service.TbGoodsService;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import freemarker.template.TemplateException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author DELL
* @description 针对表【tb_goods】的数据库操作Service实现
* @createDate 2024-07-03 15:45:15
*/
@Service
public class TbGoodsServiceImpl extends ServiceImpl<TbGoodsMapper, TbGoods>
    implements TbGoodsService{

    @Autowired
    TbGoodsMapper tbGoodsMapper;
    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    TbSortMapper tbSortMapper;
    @Autowired
    OSSFileUtil ossFileUtil;
    @Autowired
    TbSpecMapper tbSpecMapper;
    @Autowired
    TbImageMapper tbImageMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TbActivityMapper tbActivityMapper;
    @Override
    public R TbGoodsList(PageInfoVo pageInfoVo) {

        Page<TbGoods> tbGoodsPage=new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());

        QueryWrapper<TbGoods> tbGoodsQueryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(pageInfoVo.getKeyWord())) {
            tbGoodsQueryWrapper.lambda().like(TbGoods::getGoodsName,pageInfoVo.getKeyWord());
        }
        if (pageInfoVo.getSortId1()!=null&& !pageInfoVo.getSortId1().equals(0)) {
            tbGoodsQueryWrapper.lambda().eq(TbGoods::getSortId1,pageInfoVo.getSortId1());
        }
        if (pageInfoVo.getSortId2()!=null&& !pageInfoVo.getSortId2().equals(0)) {
            tbGoodsQueryWrapper.lambda().eq(TbGoods::getSortId2,pageInfoVo.getSortId2());
        }
        if (pageInfoVo.getStatus()!=null&& !pageInfoVo.getStatus().equals(0)) {
            tbGoodsQueryWrapper.lambda().eq(TbGoods::getGoodsStatus,pageInfoVo.getStatus());
        }

        tbGoodsQueryWrapper.lambda().orderByDesc(TbGoods::getUpdateTime);

        Page<TbGoods> goodsPage = tbGoodsMapper.selectPage(tbGoodsPage, tbGoodsQueryWrapper);

        return R.OK(goodsPage);

    }

    @Override
    public R TbSortList(Integer id) {

        List<TbSort> tbSorts = tbSortMapper.selectList(new QueryWrapper<TbSort>().lambda().eq(TbSort::getLinkageId, id));

        return R.OK(tbSorts);
    }

    @Override
    public R OssUpload(MultipartFile file) throws IOException {

        String url = ossFileUtil.uploadFileByBreakingPoint(file);
        return R.OK(url);
    }

    @Override
    @Transactional
    public R saveGoods(TbGoodsVo tbGoodsVo) {

        //创建时间
        tbGoodsVo.getTbGoods().setCreateTime(new Date());
        //状态
        tbGoodsVo.getTbGoods().setGoodsStatus(0);
        //修改时间
        tbGoodsVo.getTbGoods().setUpdateTime(tbGoodsVo.getTbGoods().getCreateTime());
        //商品价格
        tbGoodsVo.getTbGoods().setGoodsPrice(BigDecimal.valueOf(200));
        //商品库存
        tbGoodsVo.getTbGoods().setGoodsNum(99);
        //商品保存
        tbGoodsMapper.insert(tbGoodsVo.getTbGoods());

        for (TbSpec tbSpec : tbGoodsVo.getTbSpecs()) {
            TbSpec spec=new TbSpec();
            spec.setGoodsId(tbGoodsVo.getTbGoods().getGoodsId());
            spec.setCreateTime(new Date());
            spec.setSpecName(tbSpec.getSpecName());
            spec.setSpecImage(tbSpec.getSpecImage());
            spec.setCostPrice(tbSpec.getCostPrice());
            spec.setSpecSubvalue(tbSpec.getSpecSubvalue());
            spec.setSpecValue(tbSpec.getSpecValue());
            spec.setSalesVolume(tbSpec.getSalesVolume());
            spec.setSellingPrice(tbSpec.getSellingPrice());
            spec.setSpecNum(tbSpec.getSpecNum());
            spec.setSupplyPrice(tbSpec.getSupplyPrice());
            tbSpecMapper.insert(spec);
        }

        Integer goodsId = tbGoodsVo.getTbGoods().getGoodsId();
        for (TbImage image : tbGoodsVo.getImages()) {
            image.setGoodsId(goodsId);
            tbImageMapper.insert(image);
        }

        return R.OK();
    }

    @Override
    public R recommend(Integer id, Integer right) throws TemplateException, IOException {
        //推荐
        if (right==1) {

            TbGoods tbGoods = tbGoodsMapper.selectById(id);


            String key="ID-"+tbGoods.getGoodsId();

            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(tbGoods.getUpdateTime()));

            tbGoods.setUpdateTime(new Date());


            tbGoodsMapper.updateById(tbGoods);
            FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
            HashMap<String,Object> map=new HashMap();
            TbGoods selectById = tbGoodsMapper.selectById(id);
            List<TbGoods> tbGoodsList = tbGoodsMapper.selectList(new QueryWrapper<TbGoods>().lambda().eq(TbGoods::getGoodsId, id));
            map.put("goods",selectById);
            map.put("goodsList",tbGoodsList);

            freemarkerUtil.createHtml(map,"goods","D:\\free\\goods"+id+".html");
            return R.OK();

        }else {
            //取消推荐

            //查询是否存在
            TbGoods tbGoods = tbGoodsMapper.selectById(id);

            String key="ID-"+id;
            String s = stringRedisTemplate.opsForValue().get(key);
            Date date = JSON.parseObject(s, Date.class);
            System.out.println(date);
            //修改以前的时间

            tbGoods.setUpdateTime(date);

            tbGoodsMapper.updateById(tbGoods);
            FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
            HashMap<String,Object> map=new HashMap();
            TbGoods selectById = tbGoodsMapper.selectById(id);
            List<TbGoods> tbGoodsList = tbGoodsMapper.selectList(new QueryWrapper<TbGoods>().lambda().eq(TbGoods::getGoodsId, id));
            map.put("goods",selectById);
            map.put("goodsList",tbGoodsList);

            freemarkerUtil.createHtml(map,"goods","D:\\free\\goods"+id+".html");
            return R.OK();
        }
    }

    @Override
    public R TbActivityList() {

        //活动列表
        List<TbActivity> tbActivities = tbActivityMapper.selectList(null);

        //统一返回类
        return R.OK(tbActivities);
    }

    @Override
    public R saveTbActivity(TbActivity tbActivity) {

        //保存活动信息
        int insert = tbActivityMapper.insert(tbActivity);

        //统一返回类
        return R.OK();
    }

    @Override
    public R userLogin(TbUser tbUser) {

        //判断用户名是否为空
        if (StringUtils.isEmpty(tbUser.getUserName())) {
            return R.ERROR(500,"用户名不能为空");
        }
        //判断密码是否为空
        if (StringUtils.isEmpty(tbUser.getUserPass())) {
            return R.ERROR(500,"密码不能为空");
        }

        //查询用户名是否存在
        TbUser selectOne = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, tbUser.getUserName()));
        if (selectOne==null) {
            return R.ERROR(500,"用户名为空,请去注册");
        }

        //判断密码是否正确

        String bcrypt = DigestUtil.bcrypt(tbUser.getUserPass());
        System.out.println(bcrypt);

        boolean b = DigestUtil.bcryptCheck(tbUser.getUserPass(), selectOne.getUserPass());

        if (!b) {
            return R.ERROR(500,"密码为空");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie")
                .claim("id", selectOne.getUserId())
                .compact();

        //存到缓存中
        String key="TOKEN-"+selectOne.getUserId();
        stringRedisTemplate.opsForValue().set(key,token,60, TimeUnit.MINUTES);

        selectOne.setUserPass(null);

        selectOne.setToken(token);
        return R.OK(selectOne);
    }

    @Override
    public R getByIdGoods(Integer id) throws TemplateException, IOException {

       return null;
    }
}




